<template>
  <div class="app-container">
    <el-form :inline="true" :model="filters" ref="ruleForm" class="demo-form-inline">
      <el-form-item label="账户名：">
        <el-input v-model="filters.userName" placeholder="请输入账户名" @keyup.enter.native="submitFilterForm"></el-input>
      </el-form-item>
      <el-form-item label="班次：">
        <el-select
          v-model="filters.work" placeholder="请选择班次">
          <el-option :label="'全部'" :value="-1"></el-option>
          <el-option :label="'早班'" :value="1"></el-option>
          <el-option :label="'中班'" :value="2"></el-option>
          <el-option :label="'晚班'" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="条件：">
        <el-select
          :collapse-tags="true"
          v-model="filters.conditionIds" width="100%" multiple placeholder="请选择条件" class="with-pre-userLevel">
          <el-option
            v-for="item in conditionList"
            :label="item.conditionName"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三方出款商户：">
        <el-select
          v-model="filters.merchantId" width="100%" placeholder="请选择三方出款商户">
          <el-option :label="'全部'" :value="-1"></el-option>
          <el-option
            v-for="item in merchantCodeList"
            :label="item.merchantName"
            :key="item.merchantId"
            :value="item.merchantId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select
          v-model="filters.status" placeholder="请选择状态">
          <el-option :label="'全部'" :value="-1"></el-option>
          <el-option :label="'关闭'" :value="0"></el-option>
          <el-option :label="'开启'" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="submitFilterForm">搜索</el-button>
      <el-button @click="cancel()">重置</el-button>
    </el-form>
    <div style="padding: 20px 0">
      <el-button-group>
        <el-button size="mini" style="width: 140px" type="primary" v-if="roleCheck('withdraw-account-add')" @click="openDialog({props:conditionList,dialogName: staticDialogName1})">批量添加分单账户</el-button>
      </el-button-group>
      <el-button-group>
        <el-button size="mini" style="width: 140px" type="primary" v-if="roleCheck('withdraw-account-set')" @click="setSingleAll">设置分单账户</el-button>
      </el-button-group>
      <el-button-group>
        <el-button size="mini" type="primary" v-if="roleCheck('withdraw-account-open')" @click="setStatusAll(1)">开启</el-button>
      </el-button-group>
      <el-button-group>
        <el-button size="mini" type="primary" v-if="roleCheck('withdraw-account-close')" @click="setStatusAll(0)">关闭</el-button>
      </el-button-group>
      <el-button-group>
        <el-button type="danger" v-if="roleCheck('withdraw-del-all')" @click="delStatus(1)">批量删除</el-button>
      </el-button-group>
    </div>
    <el-table @selection-change="handleSelectionChange"
              ref="multipleTable"
              :data="tableData.list"
              v-loading="loading"
              element-loading-text="加载中..."
              class="el-table-align-center">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="账户名" prop="userName" align="center" ></el-table-column>
      <el-table-column label="班次" prop="work" align="center">
        <template slot-scope="{row}">
          {{row.work | toConverter('SHIFT_TYPE')}}
        </template>
      </el-table-column>
      <el-table-column label="条件" prop="conditionName" align="center">
        <template slot-scope="{row}">
          <span
            style="color: #409eff;cursor: pointer"
            @click="openConditionDialog(row.conditionId)"
            type="text">{{row.conditionName}} {{row.conditionId.split(',').length > 1 ? '等'+row.conditionId.split(',').length+'个条件': ''}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="三方出款商户总数" prop="merchantCount" align="center">
        <template slot-scope="{row}">
          <el-button
            @click="row.merchantCount>0? openMerchantCountDialog(row.merchantId):''"
            type="text">{{row.merchantCount}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="账户添加时间"prop="createDate" align="center">
        <template slot-scope="{row}">
          <div>{{row.createDate | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column label="账户添加人" prop="creator" align="center"></el-table-column>
      <el-table-column label="修改时间" prop="lastUpdate" align="center">
        <template slot-scope="{row}">
          <div>{{row.lastUpdate | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column label="修改人" prop="lastOperator" align="center"></el-table-column>
      <el-table-column label="状态 " prop="status" align="center">
        <template slot-scope="{row}">
          {{row.status == 0 ? '关闭' : '开启'}}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template slot-scope="{row}">
          <el-button type="text" v-if="roleCheck('withdraw-setting')" @click="setSingle(row.id,row.userName,row.conditionId,row.remark)">设置</el-button>
          <!--关闭的只能开启，开启的只能关闭-->
          <el-button type="text" @click="setStatus(row.status,row.id)">{{row.status == 1 ? '关闭' : '开启'}}</el-button>
          <el-button type="text" v-if="roleCheck('withdraw-del')" @click="delStatus(2,row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>
    <batch-user-dialog
      v-if="dialogName === staticDialogName1"
      :row-data="dialogProps"
      v-model="dialogVisible"
      @useradd="tempFn"
      @submit="submitFinished"/>
    <setting-user-dialog
      v-if="dialogName === staticDialogName2"
      :row-data="dialogProps"
      v-model="dialogVisible"
      @useradd="_tempFn"
      @submit="submitFinished"/>
    <el-dialog :visible.sync="conditionDialog" :before-close="cancel1" >
      <template slot="title">条件</template>
      <el-table
        border
        :data="conditionView"
        v-loading="loading"
        element-loading-text="加载中..."
        class="el-table-align-center">
        <el-table-column label="条件名称" prop="conditionName" align="center"></el-table-column>
        <el-table-column label="金额区间" align="center">
          <template slot-scope="{row}">
            {{row.minAmount}} - {{row.maxAmount}}
          </template>
        </el-table-column>
        <el-table-column label="提现类型" prop="withdrawType" align="center">
          <template slot-scope="{row}">
            {{row.withdrawType == 0 ? '人工出款' : '三方手动出款'}}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="conditionDialog = false">取 消</el-button>
        <el-button type="primary" @click="conditionDialog = false">确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="merchantCountDialog" :before-close="cancel2" >
      <template slot="title">三方出款商户总数</template>
      <el-table
        border
        :data="merchantView"
        v-loading="loading"
        element-loading-text="加载中..."
        class="el-table-align-center">
        <el-table-column label="三方出款商户" prop="channelName" align="center"></el-table-column>
        <el-table-column label="商户号" prop="merchantCode" align="center"></el-table-column>
        <el-table-column label="三方账户余额" align="center">
          <template slot-scope="{row}">
            {{row.amount}}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="merchantCountDialog = false">取 消</el-button>
        <el-button type="primary" @click="merchantCountDialog = false">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  withdrawAccountList, withdrawConditionList, accountSwitch, accountDelete, conditionReview, merchantReview, accountBalance,
} from '@/services/api/withdraw';
import { paymentWithdrawOverview } from '@/services/api/payment';
import { grid, dialog } from '@/build';
import BatchUserDialog from '@/views/finance/withdraw/batchUserDialog';
import SettingUserDialog from '@/views/finance/withdraw/settingUserDialog';

export default {
  name: 'single-account',
  components: { BatchUserDialog, SettingUserDialog },
  mixins: [grid, dialog],
  data() {
    return {
      conditionId: [],
      staticDialogName1: 'batch-user-dialog',
      staticDialogName2: 'setting-user-dialog',
      conditionDialog: false,
      merchantCountDialog: false,
      ids: [],
      merchantCodeList: [],
      filters: {
        size: 20,
        page: 1,
        userName: undefined,
        work: -1,
        status: -1,
        conditionIds: [],
        merchantId: -1,
      },
      conditionList: [],
      merchantView: [],
      conditionView: [],
      dialogVisible: false,
      tableData: {
        list: [],
      },
      conditionIdsView: '',
      merchantIdsView: '',
    };
  },
  computed: {
    idsArr() {
      return this.ids.map(item => ({
        value: item.id,
        title: item.userName,
      }));
    },
    _idsArr() {
      return this.ids.map(item => item.id);
    },
  },
  mounted() {
    this.bindGet(withdrawAccountList, 'tableData', {
      action: 'getGrid',
      beforeSend: () => ({
        ...this.filters,
        conditionIds: this.filters.conditionIds.join(','),
      }),
    });
    this.bindGet(withdrawConditionList, 'conditionList', {
      action: 'getGrid1',
    });
    this.bindGet(paymentWithdrawOverview, 'merchantCodeList', {
      action: 'getGrid2',
      beforeSend: () => ({ channelId: -1 }),
    });
    this.bindGet(conditionReview, 'conditionView', {
      action: 'getConditionGrid',
      beforeSend: () => ({
        conditionIds: this.conditionIdsView,
      }),
    });
    this.bindGet(merchantReview, 'merchantView', {
      action: 'getMerchantGrid',
      beforeSend: () => ({
        merchantIds: this.merchantIdsView,
      }),
      format: (data) => {
        const arr = [];
        data.forEach((v, k) => {
          accountBalance({
            merchantId: v.merchantId,
          }).then((data) => {
            this.$set(v, 'amount', data[0] ? (data[1] == -1 ? '不支持三方账户余额查询' : data[1]) : 0);
            arr.push(v);
          });
        });
        return arr;
      },
    });
    this.doGet({ action: 'getGrid' });
    this.doGet({ action: 'getGrid1' });
    this.doGet({ action: 'getGrid2' });
    // this.getAll()
  },
  methods: {
    cancel() {
      this.filters = {
        size: 20,
        page: 1,
        userName: undefined,
        work: -1,
        status: -1,
        conditionIds: [],
        merchantId: -1,
      },
      this.doGet({ action: 'getGrid' });
    },
    cancel1() {
      this.conditionDialog = false;
    },
    cancel2() {
      this.merchantCountDialog = false;
    },
    handleSelectionChange(val) {
      this.ids = val;
      _.forEach(val, (item) => {
        if (!this.conditionId.includes(item.conditionId)) {
          this.conditionId.push(item.conditionId);
        }
      });
    },
    submitFilterForm() {
      this.gridSearch();
    },
    setSingleAll() {
      if (this.idsArr.length <= 0) {
        this.$message({
          type: 'warning',
          message: '请勾选数据',
        });
        return;
      }
      this.openDialog({ props: { idsArr: this.idsArr, conditionList: this.conditionList, conditionId: this.conditionId }, dialogName: this.staticDialogName2 });
    },
    setSingle(id, userName, conditionId, remark) {
      const idsArr = [];
      idsArr.push({
        value: id,
        title: userName,
      });
      this._tempFn({
        value: id,
        check: true,
      });
      this.openDialog({ props: {
 idsArr, conditionList: this.conditionList, conditionId,remark 
}, dialogName: this.staticDialogName2 });
    },
    setStatus(status, id) {
      if (status == 1) {
        status = 0;
      } else if (status == 0) {
        status = 1;
      }
      this.$confirm(`确定${status == 1 ? '开启' : '关闭'}当前账户的分单设置吗？`, `${status === 1 ? '开启' : '关闭'}派单`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        accountSwitch({
          status,
          accountIds: id,
        }).then(([result, data]) => {
          if (result) {
            this.doGet({ action: 'getGrid' });
            this.$message({
              type: 'success',
              message: `${status === 1 ? '开启' : '关闭'}成功!`,
            });
          } else {
            this.$message({
              type: 'error',
              message: `${status === 1 ? '开启' : '关闭'}失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },
    setStatusAll(status) {
      if (this.idsArr.length <= 0) {
        this.$message({
          type: 'warning',
          message: '请勾选数据',
        });
        return;
      }
      this.$confirm(`确定${status === 1 ? '开启' : '关闭'}选中账户的分单设置吗？`, `${status === 1 ? '开启' : '关闭'}派单`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        accountSwitch({
          status,
          accountIds: this._idsArr.join(','),
        }).then(([result, data]) => {
          if (result) {
            this.doGet({ action: 'getGrid' });
            this.$message({
              type: 'success',
              message: `${status === 1 ? '开启' : '关闭'}成功!`,
            });
          } else {
            this.$message({
              type: 'error',
              message: `${status === 1 ? '开启' : '关闭'}失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },
    //  type =>1 批量删除  2单个删除
    delStatus(type, id) {
      let idStr = '';
      if (type === 1) {
        if (this.idsArr.length <= 0) {
          this.$message({
            type: 'warning',
            message: '请勾选数据',
          });
          return;
        }
        idStr = this._idsArr.join(',');
      } else if (type === 2) {
        idStr = id;
      }
      this.$confirm('确定删除分单账户吗？', '删除分单账户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        accountDelete({
          accountIds: idStr,
        }).then(([result, data]) => {
          if (result) {
            this.doGet({ action: 'getGrid' });
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          } else {
            this.$message({
              type: 'error',
              message: `删除失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },
    openConditionDialog(conditionIds) {
      this.conditionIdsView = conditionIds;
      this.doGet({ action: 'getConditionGrid' });
      this.conditionDialog = true;
    },
    openMerchantCountDialog(merchantIds) {
      this.merchantIdsView = merchantIds;
      this.doGet({ action: 'getMerchantGrid' });
      this.merchantCountDialog = true;
    },
    tempFn(data) {
      this.gridSearch();
      setTimeout(() => {
        this.tableData.list.forEach((v, k) => {
          if (_.find(data, { id: v.id }) != undefined) {
            this.$refs.multipleTable.toggleRowSelection(v);
          }
        });
      }, 200);
    },
    _tempFn(data) {
      this.tableData.list.forEach((v, k) => {
        if (v.id == data.value) {
          this.$refs.multipleTable.toggleRowSelection(v, data.check);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
  .active{
    color:#F4A460;;
  }
  /deep/ .with-pre-userLevel .el-tag{
    max-width: 105px!important;
  }
</style>
